﻿using FreeSql;
using GalaSoft.MvvmLight.Command;
using KJSync.Access.Models;
using KJSyncXP.Access.Context;
using KJSyncXP.Sqlite.Model;
using KJSyncXP.SQLite.Context;
using log4net;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;

namespace KJSyncXP.ViewModels
{
    public class StandardSelectViewModel : BaseViewModel
    {
        private readonly SqliteDbContext _sqliteCtx;
        private readonly ILog _logger;

        public RelayCommand AddButtonCommand { get; private set; }
        public RelayCommand DeleteButtonCommand { get; private set; }
        public RelayCommand ClearCommand { get; private set; }

        // 胶料号集合
        private ObservableCollection<StandardProduct> _standardProducts = new ObservableCollection<StandardProduct>();
        public ObservableCollection<StandardProduct> StandardProducts
        {
            get => _standardProducts;
            set
            {
                _standardProducts = value;
                RaisePropertyChanged("_standardProducts");
            }
        }

        // 绑定TextBox输入的胶料号
        private string _newMaterialNumber;
        public string NewMaterialNumber
        {
            get => _newMaterialNumber;
            set
            {
                _newMaterialNumber = value?.Trim(); 
                RaisePropertyChanged("NewMaterialNumber");
            }
        }

        // 绑定DataGrid选中项
        private StandardProduct _selectedProduct;
        public StandardProduct SelectedProduct
        {
            get => _selectedProduct;
            set
            {
                _selectedProduct = value;
                RaisePropertyChanged("SelectedProduct");
            }
        }

        public StandardSelectViewModel(log4net.ILog log, SqliteDbContext sqliteCtx )
        {
            _sqliteCtx = sqliteCtx;
            _logger = log;

            DeleteButtonCommand = new RelayCommand(Delete);
            AddButtonCommand = new RelayCommand(Add);
            ClearCommand = new RelayCommand(Clear);
            LoadStandardProduct();
        }

        public void LoadStandardProduct()
        {
            var reslist =  _sqliteCtx.Db.Queryable<StandardProduct>().OrderBy(w => w.Id).ToList();
            StandardProducts = new ObservableCollection<StandardProduct>(reslist);           
        }


        public void Add()
        {
            try
            {
                if(NewMaterialNumber == string.Empty)
                {
                    MessageBox.Show("胶料号不能为空！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }
                else
                {
                    // 创建新胶料号实体
                    var newProduct = new StandardProduct
                    {
                        ProductNumber = NewMaterialNumber,
                    };
                    // 插入数据库
                    _sqliteCtx.Db.Insert(newProduct).ExecuteAffrows();
                    // 刷新DataGrid（添加到ObservableCollection会自动触发UI更新）
                    StandardProducts.Add(newProduct);
                    // 清空输入框
                    NewMaterialNumber = string.Empty;
                    _logger.Info($"成功添加胶料号：{NewMaterialNumber}");
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"添加胶料号「{NewMaterialNumber}」失败", ex);               
            }
        }
        public void Delete() {

            if (SelectedProduct !=null)
            {
                var result = MessageBox.Show($"确定要删除胶料号 '{SelectedProduct.ProductNumber}' 吗？",
                                           "确认删除",
                                           MessageBoxButton.YesNo,
                                           MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                   _sqliteCtx.Db.Delete<StandardProduct>().Where(w => w.Id == SelectedProduct.Id).ExecuteAffrows();
                    StandardProducts.Remove(SelectedProduct);
                    SelectedProduct = null;
                    _logger.Info($"成功删除胶料号：{SelectedProduct?.ProductNumber}");

                }
            }
            else
            {
                MessageBox.Show("请先选择要删除的胶料号！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        public void Clear() {

            try
            {
                if (StandardProducts.Count == 0)
                {
                    MessageBox.Show("表格已为空！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                var result = MessageBox.Show("确定要清空所有胶料号记录吗？",
                                           "确认清空",
                                           MessageBoxButton.YesNo,
                                           MessageBoxImage.Warning);

                if (result == MessageBoxResult.Yes)
                {
                    int deleteCount = _sqliteCtx.Db.Delete<StandardProduct>()
                                               .Where("1=1") 
                                               .ExecuteAffrows();

                    if (deleteCount > 0)
                    {
                        StandardProducts.Clear();
                        _logger.Info($"成功清空所有胶料号，共删除 {deleteCount} 条记录");
                        MessageBox.Show("清空成功！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    else
                    {
                        MessageBox.Show("清空失败，无记录可删除！", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("清空胶料号失败", ex);
            }
            
        }
    }
}
